<?php

namespace app\adminapi\controller;

use app\helpers\Common;

use support\Request;
use support\think\Db;
use think\Exception;

class ArticleCateController extends BaseController
{
    public function initialize()
    {
        parent::initialize();

        $this->modelName = 'ArticleCate';
        $this->defaultOrder = 'sorting ASC, created_at DESC';
    }

    /**
     * List
     */
    public function list(Request $request)
    {
        $param = $request->all();

        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;
        $field = $this->defaultField;
        $where = $this->getFilterWhere($request);
        if ($this->defaultWhere) {
            $where = array_merge($this->defaultWhere, $where);
        }
        if ($this->defaultOrder) {
            $order = $this->defaultOrder;
        }

        $list = $model->where($where)->field($field)->order($order)->select()->toArray();
        if ($list) {
            // 处理列表数据
            $list = $this->handleListData($list);
        }
        $data = [
            'data' => $list
        ];

        return api_response(self::STATUS_SUCCESS, '', $data);
    }

    /**
     * Eval data for post data save
     *
     * @param Request $request
     * @return array
     */
    protected function evalData($request)
    {
        $param = $request->all();

        $data = [
            'id' => $param['id'],
            'parent_id' => $param['parent_id'],
            'name' => $param['name'],
            'sub_name' => $param['sub_name'],
            'sorting' => $param['sorting'],
            'status' => $param['status'],
        ];

        return $data;
    }

    /**
     * 处理列表数据
     */
    protected function handleListData($data)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;

        $data = $model->formatDatas($data, ['format_source' => 'backend']);
        $data = list_to_tree($data, 'id', 'parent_id', 'children', 0);

        return $data;
    }
}
